package com.bungarus.om.busi;

import com.bungarus.config.BungarusSpringConfig;
import com.bungarus.offline.OfflineMessage;
import com.bungarus.offline.OfflineMessagePersist;
import com.bungarus.om.model.OfflineMessageOps;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.ApplicationContext;
import org.springframework.context.annotation.AnnotationConfigApplicationContext;
import org.springframework.context.annotation.Bean;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.stereotype.Component;

import java.util.List;

@Component
public class OfflineMessageManager {
    private static final ApplicationContext springContext =
            new AnnotationConfigApplicationContext(BungarusSpringConfig.class);

    private OfflineMessageOps getOfflineMessageOps(){
        return OfflineMessageOps.getInstance(getMongoTemplate4FailedRetry());
    }

    public List<OfflineMessage> retriveOfflineMessages(int tenantId, String userId, String app, String dev, int offset, int size){
        List<OfflineMessage> messages = getOfflineMessageOps().retrieveByUser(tenantId, userId, app, dev, offset, size);
        //String content = StringUtils.collectionToDelimitedString(contents, messageDelimiter);
        return messages;
    }

    public void updateOfflineMessagePointer(int tenantId, String uid, String app, String dev, long newPointer){
        getOfflineMessageOps().updatePointerByUser(tenantId, uid, app, dev, newPointer);
    }

    public long getCurrentOfflineMessagePointerOffset(int tenantId, String uid, String dev){
        return getOfflineMessageOps().getOfflinePointerOffset(tenantId, uid, dev);
    }

    public MongoTemplate getMongoTemplate4FailedRetry() {
        return (MongoTemplate) springContext.getBean("mongoTemplate");
    }
}
